import 'package:flutter/material.dart';
import 'package:flutter_printer_plugin_example/constants.dart';
import 'dart:async';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/services.dart';
import 'package:flutter_printer_plugin/flutter_printer_plugin.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver{
  String _platformVersion = 'Unknown';
  final _flutterPrinterPlugin = FlutterPrinterPlugin();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addObserver(this);
    initPlatformState();
    _init();
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    _free();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if(state == AppLifecycleState.resumed){
      _init();
    }else if(state == AppLifecycleState.paused){
      _free();
    }
  }

  void _getVersion() async {
    try {
      String version = await _flutterPrinterPlugin.getVersion() ?? 'unkown ';
      print("_MyAppState _getVersion : '$version' ");
      Fluttertoast.showToast(
        msg: "_getVersion '$version'",
        toastLength: Toast.LENGTH_LONG,
      );
    } on PlatformException catch (e) {
      print("MyAppState _getVersion error: '${e.message}'.");
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: ListView(
            children: <Widget>[
              Text('Running on: $_platformVersion\n'),
             /* ElevatedButton(
                onPressed: _isSupportPrinter,
                child: const Text('是否支持打印'),
              ),
              ElevatedButton(
                onPressed: _init,
                child: const Text('初始化打印机设备'),
              ),*/
              ElevatedButton(
                onPressed: _free,
                child: const Text('释放打印机设备'),
              ),
              ElevatedButton(
                onPressed: _sendData,
                child: const Text('发送数据到打印机'),
              ),
              ElevatedButton(
                onPressed: _printText,
                child: const Text('打印文本内容'),
              ),
              ElevatedButton(
                onPressed: _printImage,
                child: const Text('打印图片内容'),
              ),
              ElevatedButton(
                onPressed: _printBarcode,
                child: const Text('打印条形码'),
              ),
              ElevatedButton(
                onPressed: _setFeedRow,
                child: const Text('设置走纸行数'),
              ),
              ElevatedButton(
                onPressed: _setGPSMode,
                child: const Text('设置GPS模式'),
              ),
              ElevatedButton(
                onPressed: _setPrintRowSpacing,
                child: const Text('设置打印行间距'),
              ),
              ElevatedButton(
                onPressed: _setPrintLeftMargin,
                child: const Text('设置打印左边距'),
              ),
              ElevatedButton(
                onPressed: _setPrintAlignmentMode,
                child: const Text('设置打印对齐模式'),
              ),
              ElevatedButton(
                onPressed: _setPrintSpeed,
                child: const Text('设置打印速度'),
              ),
              ElevatedButton(
                onPressed: _setPrintChromaLevel,
                child: const Text('设置打印色度级别'),
              ),
              ElevatedButton(
                onPressed: _restoreDefault,
                child: const Text('恢复默认设置'),
              ),
              ElevatedButton(
                onPressed: Black_label_On,
                child: const Text('开启热敏打印'),
              ),
              ElevatedButton(
                onPressed: Black_label_Off,
                child: const Text('关闭热敏打印'),
              ),
              ElevatedButton(
                onPressed: Feed_to_Next,
                child: const Text('跳到下一个打印'),
              ),
              ElevatedButton(
                onPressed: _setBarcodeHeight,
                child: const Text('设置条形码高度'),
              ),
              ElevatedButton(
                onPressed: _setBarcodeWidth,
                child: const Text('设置条形码宽度'),
              ),
              ElevatedButton(
                onPressed: _setBarcodeHRI,
                child: const Text('设置条形码HRI位置'),
              ),
              ElevatedButton(
                onPressed: _setUnderlineMode,
                child: const Text('设置下划线模式'),
              ),
              ElevatedButton(
                onPressed: _setBoldMode,
                child: const Text('设置粗体模式'),
              ),
              ElevatedButton(
                onPressed: _setFontDimension,
                child: const Text('设置字体尺寸'),
              ),
              ElevatedButton(
                onPressed: _getBaudRate,
                child: const Text('获取波特率'),
              ),
              ElevatedButton(
                onPressed: _getVersion,
                child: const Text('获取版本号')
                ),
              ElevatedButton(
                onPressed: _getFontVersion,
                child: const Text('获取字体版本号')
                ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await _flutterPrinterPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  void _init() async {
    try {
      print("_MyAppState _init  start ");
      String success = await _flutterPrinterPlugin.init() ?? 'unkown ';
      print("_MyAppState _init  end: '$success' ");
      Fluttertoast.showToast(
        msg: "init '$success'",
        toastLength: Toast.LENGTH_LONG,
      );
    } on PlatformException catch (e) {

    }
  }

  void _isSupportPrinter() async {
    try {
      String success = await _flutterPrinterPlugin.isSupportPrinter() ?? 'unkown ';
      print("_MyAppState _isSupportPrinter : '$success' ");
    } on PlatformException catch (e) {}
  }

  void _free() async {
    try {
      print("_MyAppState _free  start");
      String success = await _flutterPrinterPlugin.free() ?? 'unkown ';
      print("_MyAppState _free  end: '$success' ");
      Fluttertoast.showToast(
        msg: "free '$success'",
        toastLength: Toast.LENGTH_LONG,
      );
    } on PlatformException catch (e) {}
  }

  void _sendData() async{
    //byte[]数组命令--->需要转成字符串形式
    String success = await _flutterPrinterPlugin.sendData("") ?? 'unkown ';
  }

  void _printText() async{
    _flutterPrinterPlugin.printText("123456", "gbk") ?? 'unkown ';
    _flutterPrinterPlugin.setFeedRow(0, 5);
  }

  void _printImage() async{
    // encode base64
    await _flutterPrinterPlugin.print(Constants.IMG_BASE64,
          33,30,                //mode,interval(decide printer speed)
         380,480) ?? 'unkown '; //width,height
    _flutterPrinterPlugin.setFeedRow(0, 3);
  }

  void _printBarcode() async{
    _flutterPrinterPlugin.initPrint();
    _flutterPrinterPlugin.printBarcode("12345678911", "UPC_A");
    _flutterPrinterPlugin.setFeedRow(0, 3);
  }

  void _setFeedRow() async {
    _flutterPrinterPlugin.setFeedRow(0, 3);
  }

  void _setGPSMode() async {
    _flutterPrinterPlugin.setGSPMode(0, 0);
  }

  void _setPrintRowSpacing() async{
    _flutterPrinterPlugin.setPrintRowSpacing(10);
  }

  void _setPrintLeftMargin() async{
    _flutterPrinterPlugin.setPrintLeftMargin(5,5);
  }

  void _setPrintAlignmentMode() {
    _flutterPrinterPlugin.setPrintAlignmentMode(1);
  }

  void _setPrintSpeed() {
    _flutterPrinterPlugin.setPrintSpeed(200);
  }

  void _setPrintChromaLevel() {
    _flutterPrinterPlugin.setPrintChromaLevel(25);
  }

  void _restoreDefault() {
    _flutterPrinterPlugin.restoreDefault();
  }

  void Black_label_On() {
    _flutterPrinterPlugin.Black_label_On();
  }

  void Black_label_Off() {
    _flutterPrinterPlugin.Black_label_Off();
  }

  void Feed_to_Next() {
    _flutterPrinterPlugin.Feed_to_Next();
  }

  void _setBarcodeHeight() {
    _flutterPrinterPlugin.setBarcodeHeight(200);
  }

  void _setBarcodeWidth() {
    _flutterPrinterPlugin.setBarcodeWidth(5);
  }

  void _setBarcodeHRI() {
    _flutterPrinterPlugin.setBarcodeHRI(2);
  }

  void _setUnderlineMode() {
    _flutterPrinterPlugin.setUnderlineMode(1);
  }

  void _setBoldMode() {
    _flutterPrinterPlugin.setBoldMode(1);
  }

  void _setFontDimension() {
    _flutterPrinterPlugin.setFontDimension(17);
  }

  void _getBaudRate() async{
    String baudRate = await _flutterPrinterPlugin.getBaudRate()?? '';
    print("_MyAppState _getBaudRate '$baudRate' ");
    Fluttertoast.showToast(
      msg: "_getBaudRate '$baudRate'",
      toastLength: Toast.LENGTH_LONG,
    );
  }

  void _getFontVersion() async{
    String fontVersion = await _flutterPrinterPlugin.getFontVersion()?? '';
    print("_MyAppState _getFontVersion '$fontVersion' ");
    Fluttertoast.showToast(
      msg: "_getFontVersion '$fontVersion'",
      toastLength: Toast.LENGTH_LONG,
    );
  }
}
